package com.example.bigworkdemo.web.interceptor;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RunTimeInterceptor implements HandlerInterceptor{
	private ThreadLocal<Long> start = new ThreadLocal<>();
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		start.set(System.currentTimeMillis());

		return true;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		System.out.print(df.format(new Date())+"|");// new Date()为获取当前系统时间
		System.out.print(request.getMethod()+"|");
		System.out.print((request.getRequestURI()+"|"));
//		Thread.sleep(3000);
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//结束时间-开始时间=执行时间
		long end = System.currentTimeMillis();
		long time = end - start.get();
		System.out.println(time);
	}
}
